package com.cuitrip.business.login.proxy;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;

import com.cuitrip.apiservice.UserBusiness;
import com.cuitrip.business.home.IndexActivity;
import com.cuitrip.business.login.LoginActivity;
import com.cuitrip.business.login.LoginInstance;
import com.cuitrip.business.login.RegisterActivity;
import com.cuitrip.business.login.UserEnterActivity;
import com.cuitrip.business.login.model.ThirdAccount;
import com.cuitrip.business.user.model.CtUserInfo;
import com.cuitrip.business.webview.H5UrlMaker;
import com.cuitrip.util.track.TrackScreenName;
import com.cuitrip.util.track.TrackUtil;
import com.lab.jumper.Jumper;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.rtenvironment.AppCoreRuntime;
import com.lab.utils.LogHelper;
import com.lab.utils.MessageUtils;

/**
 * 登录相关逻辑
 * Created by ak on 15/9/23.
 */
public class LoginProxy implements IProxyCallback {

    public static final int REQUEST_LOGIN = 1000;

    public static final int GO_REGISTEER = 10001;

    private static LoginProxy sInstance;

    private ApiProxy mApiProxy = new ApiProxy(this);


    public static LoginProxy getInstance() {
        if (null == sInstance)
            sInstance = new LoginProxy();
        return sInstance;
    }

    public void gotoLogin(Activity activity) {
        TrackUtil.trackScreenName("/account/login");
        Jumper.launchActivityForResult(activity, new Intent(activity, LoginActivity.class), REQUEST_LOGIN);
    }

    public void gotoUserEnter(Activity activity) {
        TrackUtil.trackScreenName(TrackScreenName.PRE_LOGIN);
        Jumper.launchActivityForResult(activity, new Intent(activity, UserEnterActivity.class), REQUEST_LOGIN);
    }

    public void gotoUserEnter(Context context) {
        TrackUtil.trackScreenName(TrackScreenName.PRE_LOGIN);
        Jumper.launchActivity(context, new Intent(context, UserEnterActivity.class));
    }

    public void gotoRegister(Activity activity) {
        TrackUtil.trackScreenName("/account/sign_up");
        Jumper.launchActivityForResult(activity, new Intent(activity, RegisterActivity.class), GO_REGISTEER);
    }

    public void gotoFindPassword(Activity activity) {
        TrackUtil.trackScreenName("/account/reset_password");
        Uri uri = Uri.parse(H5UrlMaker.getPasswordForget());
        Intent intent = new Intent(Intent.ACTION_VIEW, uri);
        activity.startActivity(intent);
    }

    public void login(String account, String password, final CallBack callback) {
        ApiProxy apiProxy = new ApiProxy(new IProxyCallback() {
            @Override
            public boolean onProxyResult(ProxyResult<?> result) {
                CtApiResponse response = (CtApiResponse) result.getData();
                if (response.isResponseNormal()) {
                    if (response.result instanceof CtUserInfo) {
                        if (response.result != null) {
                            loginSuccess((CtUserInfo) response.result);
                        }
                        callback.onLoginSuccess(response.result);
                    }
                } else {
                    if (response != null && !TextUtils.isEmpty(response.msg)) {
                        MessageUtils.showToast(response.msg);
                    }
                    callback.onLoginFail(0, response.msg);
                }
                return false;
            }
        });
        UserBusiness.login(apiProxy, account, password);
    }

    public void loginSuccess(CtUserInfo info) {
        ApiProxy apiProxy = new ApiProxy(new IProxyCallback() {
            @Override
            public boolean onProxyResult(ProxyResult<?> result) {
                return false;
            }
        });
        UserBusiness.updateDeviceToken(apiProxy, info);
        info.setType(CtUserInfo.USER_TRAVEL);
        CtUserInfo oldInfo = LoginInstance.getInstance().getUserInfo();
        if (oldInfo == null || (oldInfo != null && !oldInfo.isTravel())) {
            LoginInstance.update(AppCoreRuntime.context, info, true);
        } else {
            LoginInstance.update(AppCoreRuntime.context, info, true);
        }
    }

    public void thirdLogin(final ThirdAccount thirdAccount, final CallBack callback, String countryCode, String phoneNum, String vcode) {

        ApiProxy apiProxy = new ApiProxy(new IProxyCallback() {
            @Override
            public boolean onProxyResult(ProxyResult<?> result) {
                CtApiResponse response = (CtApiResponse) result.getData();
                if (response.isResponseNormal()) {
                    if (response.result instanceof CtUserInfo) {
                        loginSuccess((CtUserInfo) response.result);
                        callback.onLoginSuccess(response.result);
                    }

                } else {
                    if (response != null) {
                        callback.onLoginFail(response.code, response.msg);
                    } else {
                        callback.onLoginFail(0, "");
                    }
                }
                return false;
            }
        });
        UserBusiness.loginThirdAccount(apiProxy, thirdAccount, phoneNum, countryCode, vcode);
    }

    public void thirdLogin(final ThirdAccount thirdAccount, final CallBack callback, String email) {
        ApiProxy apiProxy = new ApiProxy(new IProxyCallback() {
            @Override
            public boolean onProxyResult(ProxyResult<?> result) {
                CtApiResponse response = (CtApiResponse) result.getData();
                if (response.isResponseNormal()) {
                    if (response.result instanceof CtUserInfo) {
                        loginSuccess((CtUserInfo) response.result);
                        callback.onLoginSuccess(response.result);
                    }

                } else {
                    if (response != null) {
                        callback.onLoginFail(response.code, response.msg);
                    } else {
                        callback.onLoginFail(0, "");
                    }
                }
                return false;
            }
        });
        UserBusiness.loginThirdAccount(apiProxy, thirdAccount, email);
    }

    public void reloginWithRestartActivity(Activity activity) {
        Intent intent = new Intent(activity, IndexActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(intent);
    }

    /**
     * String deviceId = UmengRegistrar.getRegistrationId(this);
     * <p/>
     * should  build new api  post only  deviceId ，then server delete this id
     */
    public void cleanDeviceToken(boolean force) {
        LogHelper.e("LoginActivity", "device_id: clean");
        CtUserInfo userInfo = LoginInstance.getInstance().getUserInfo();
        if (userInfo != null) {
            //如果被强制登出,不需要传入userinfo
            UserBusiness.updateDeviceToken(mApiProxy, "emptydevicetokenuser" + userInfo.getUid() + "logoutdeletetoken", force ? null : userInfo);
        }
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        return true;
    }

    public interface CallBack {

        public void onLoginSuccess(Object data);

        public void onLoginFail(int resultCode, String message);
    }


}
